package edu.cuit.avatar.concurrent;

import java.util.concurrent.Exchanger;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/17 14:30
 */
public class ExchangerTest {
    public static void main(String[] args) {
        var exchanger = new Exchanger<String>();
        new Thread(()->{
            try {
                String data = "白粉";
                System.out.println(Thread.currentThread().getName() + "正在把数据" + data +"换出去");
                Thread.sleep(100);
                //同步点进行数据的交换，等待伙伴线程到达同步点
                String $ = exchanger.exchange(data);
                System.out.println(Thread.currentThread().getName() +
                        "换回的数据为" + $);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "老白").start();

        new Thread(()->{
            try {
                String data = "美金";
                System.out.println(Thread.currentThread().getName() + "正在把数据" + data +"换出去");
                Thread.sleep(100);
                //同步点进行数据的交换，等待伙伴线程到达同步点
                String data2 = exchanger.exchange(data);
                System.out.println(Thread.currentThread().getName() +
                        "换回的数据为" + data2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "金枪客").start();
    }
}
